<template>
  <div class="alloc-resouce">
    <div v-for="p in list" :key="p.id">
      <div class="checkall-box">
        <el-checkbox
          :indeterminate="p.isIndeterminate"
          v-model="p.isCheckAll"
          @change="(val) => checkAllChange(val, p)"
          >{{ p.name }}</el-checkbox
        >
      </div>
      <el-checkbox-group
        v-model="p.checkedChild"
        @change="(val) => groupChange(val, p)"
      >
        <el-row>
          <el-col :span="8" v-for="c in p.children" :key="c.id">
            <el-checkbox :label="c.id">{{ c.name }}</el-checkbox>
          </el-col>
        </el-row>
      </el-checkbox-group>
    </div>
    <div class="btns">
      <el-button type="primary" size="small" @click="save">保存</el-button>
      <el-button size="small" @click="$router.go(-1)">取消</el-button>
    </div>
  </div>
</template>
 
<script>
import { getAllResources, getAllResourcesCate, getResurceByRoleId, updateRoleResource } from '@/request/api'
export default {
  data() {
    return {
      list: []
    }
  },
  methods: {
    save() {
      this.$confirm('是否确认修改?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const resourcIds = []
        this.list.forEach(p => {
          resourcIds.push(...p.checkedChild)
        })
        // 点击了确定
        // 向服务器同步数据
        updateRoleResource({
          roleId: this.$route.query.id,
          resourceIds: resourcIds.join()
        }).then(res => {
          if (res.code === 200) {
            this.$message.success('保存成功')
          }
        })
      }).catch(() => {
        // 点击了取消
      });
    },
    groupChange(val, p) {
      // 如果不是全选，就是半选
      p.isCheckAll = val.length === p.children.length
      p.isIndeterminate = !p.isCheckAll
    },
    checkAllChange(val, p) {
      p.checkedChild = val ? p.children.map(c => c.id) : []
      p.isIndeterminate = false // 因为我们点击分类的时候，要么全选，要么全都不选 ， 没有 半选的状态
    },
    initData() {
      Promise.all([
        getAllResources(),
        getAllResourcesCate(),
        getResurceByRoleId(this.$route.query.id)
      ]).then(res => {
        if (res[0].code === 200 && res[1].code === 200 && res[2].code === 200) {
          // 数据结构： [ { 分类 , children : [] } , {}]
          this.list = res[1].data.map(p => {
            return { id: p.id, name: p.name, children: [], isCheckAll: false, checkedChild: [], isIndeterminate: false }
          })
          res[0].data.forEach(c => {
            this.list.forEach(p => {
              if (c.categoryId == p.id) {
                p.children.push(c)
              }
            })
          })
          // 处理选中的数据
          // 1. 先把 分类再生成一个新的父数组
          const result = res[1].data.map(p => {
            return { id: p.id, name: p.name, children: [] }
          })
          // 2. 遍历第三个请求的数据，组成一个和上面得到的结构一致的数组
          res[2].data.forEach(c => {
            result.forEach(p => {
              if (c.categoryId == p.id) {
                p.children.push(c)
              }
            })
          })
          // 3. 用两个数组进行对比，设置 上面的数组 的 isCheckAll,isIndeter... , chceckChild
          for (let i = 0; i < this.list.length; i++) {
            // 如果 result里面的对象的children <已经分配给这个角色的子资源> 跟 list里面的children 个数一致就 全选
            this.list[i].isCheckAll = result[i].children.length === this.list[i].children.length
            if (result[i].children.length === 0) {
              this.list[i].isIndeterminate = false
            } else {
              this.list[i].isIndeterminate = !this.list[i].isCheckAll
            }
            // 控制 list[i].checkeChildren
            this.list[i].checkedChild = result[i].children.map(c => c.id)
          }
        }
      })
    }
  },
  created() {
    this.initData()
  }
}
</script>
 
<style lang = "less" scoped>
.alloc-resouce {
  padding: 20px;
  box-shadow: 0 0 4px 2px #ccc;
  border-radius: 4px;
}
.checkall-box {
  padding: 20px;
  background-color: #f2f6fc;
}
.el-checkbox-group {
  padding: 20px;
}
.btns {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>